package com.qjjbmt.zhq_blog_admin.controller;

import com.qjjbmt.zhq_blog_admin.pojo.User;
import com.qjjbmt.zhq_blog_admin.service.impl.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Collection;

@Controller
public class UserController {

    UserServiceImpl userService;

    public UserController(UserServiceImpl userService){
        this.userService = userService;
    }

    /**
     * 登录业务
     */
    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model, HttpSession session){
        //具体的业务
        if (!username.isEmpty() && "123456".equals(password)){
            session.setAttribute("loginUser",username);
            return "redirect:/main.html";
        }else {
            //告诉用户，你登录失败了
            model.addAttribute("msg","用户名或密码错误！");
            return "index";
        }
    }

    /**
     * 退出登录业务
     */
    @RequestMapping("/user/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "index";
    }

    /*
    查询所有用户
     */
    @RequestMapping("/users")
    public String list(Model model){
        Collection<User> users = userService.list();
        model.addAttribute("users", users);
        return "user/user_list";
    }

    /*
    跳转到添加页面
     */
    @GetMapping("/addUser")
    public String toAddUserPage(Model model){
        return "user/add";
    }

    /*
   添加用户，然后刷新列表
    */
    @PostMapping("/addUser")
    public String addUser(User user){
        LocalDateTime localDateTime = LocalDateTime.now();
        user.setRegisterTime(localDateTime);
        user.setUpdateTime(localDateTime);
        userService.save(user);
        return "redirect:/users";
    }

    /*
    根据id查询用户，然后跳转到修改页面并展示
     */
    @GetMapping("/user/{id}")
    public String toUpdateUserPage(@PathVariable("id")Integer id, Model model){
        //查出原来的数据
        model.addAttribute("user",userService.getById(id));
        return "user/update";
    }

    /*
    保存管理员的修改
     */
    @RequestMapping("/updateUser")
    public String updateUser(User user){
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
        return "redirect:/users";
    }

    /*
    根据id删除用户，然后刷新列表,并删除此评论的相关博客
     */
    @GetMapping("/delUser/{id}")
    public String deleteUser(@PathVariable("id") Integer id){
        userService.removeById(id);
        return "redirect:/users";
    }

}
